<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminBillMonth;
use App\Models\Admin\AdminCdjAuth;
use App\Models\Admin\SchoolMenu;
use App\Models\Admin\AdminSetting;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class SchoolMenuController extends AdminController
{
    use AdminTrait;

    public $model;
    public function __construct(SchoolMenu $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    public function menuList(BaseRequest $request)
    {
        $list = SchoolMenu::getAllList();
        $data = [
            'list' =>  $list,
        ];
        return $this->success($data);
    }

    public function getMenuDetail(BaseRequest $request)
    {
        $input = $request->all();
        //过滤数据
        $rule = [
            'id' => 'required|exists:school_menu,id',
        ];
        $validator = Validator::make($input, $rule, $this->vali_msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);

        $id = $input['id'];
        $info = SchoolMenu::getDetaiById($id)->toArray();
        //获取父级菜单
        $p_menu_list = SchoolMenu::getPMenuById($id);
        $active_pid = SchoolMenu::getPathById($id);
        $info['active_pid'] = array_reverse($active_pid);
        $info['p_menu_list'] = $p_menu_list;
        return $this->success($info);
    }

    public function addMenu(BaseRequest $request)
    {
        $input = $request->only('name', 'short_name', 'pid', 'controller', 'route', 'icon', 'ordid', 'display', 'action');
        //过滤数据
        $rule = [
            'name' => 'required|string',
            'short_name' => 'filled|string',
            'pid' => 'required|integer|min:0',
            'controller' => 'nullable|string',
            'route' => 'nullable|string',
            'action' => 'nullable|string',
            'icon' => 'nullable|string',
            'ordid' => 'integer|max:100',
            'display' => 'required|in:0,1',
        ];
        $validator = Validator::make($input, $rule, $this->vali_msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        DB::beginTransaction();
        try {
            $m_info = SchoolMenu::create($input);
            if (method_exists($this->model, 'addLog')) {
                $this->model->addLog($m_info, [], 1);
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error();
        }
    }

    public function editMenu(BaseRequest $request)
    {
        $input = $request->only('id', 'name', 'short_name', 'pid', 'controller', 'route', 'icon', 'ordid', 'display', 'action');
        $id = $input['id'];
        $existingRecord = SchoolMenu::where('id', $id)->first();
        if (!$existingRecord) {
            return $this->error(['-1', '记录不存在']);
        }
        //过滤数据
        $rule = [
            'id' => 'required|integer|exists:school_menu,id',
            'name' => 'string',
            'short_name' => 'string',
            'pid' => 'integer|min:0',
            'controller' => 'nullable|string',
            'route' => 'nullable|string',
            'action' => 'nullable|string',
            'icon' => 'nullable|string',
            'ordid' => 'integer|max:100',
            'display' => 'in:0,1',
        ];
        $validator = Validator::make($input, $rule, $this->vali_msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        $id = $input['id'];
        unset($input['id']);

        DB::beginTransaction();
        try {
            $model_info = $this->model->find($id);
            //赋值
            foreach ($input as $k => $v) {
                if (!is_array($v)) {
                    $model_info->$k = $v;
                }
            }
            $perInfo = $model_info->getOriginal(); //获取修改之前的字段
            //执行修改操作
            $model_info->save();
            $nextInfo = $model_info->getChanges(); //获取修改之后的字段

            if (method_exists($this->model, 'addLog')) {
                if (!empty($nextInfo)) {
                    $this->model->addLog($perInfo, $nextInfo, 2);
                }
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error();
        }
    }

    //根据父id获取子菜单
    public function menuListByPid(BaseRequest $request)
    {
        $input = $request->all();
        $rules = [
            'pid' => 'required|integer|min:0',
        ];
        $validator = Validator::make($input, $rules, $this->vali_msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        $list = SchoolMenu::getListByPid($input);
        $data = [
            'list' => $list
        ];
        return $this->success($data);
    }

    //删除菜单
    public function deleteMenu(BaseRequest $request)
    {
        $input = $request->all();
        //过滤数据
        $rule = [
            'id' => 'required|integer|min:0',
        ];
        $validator = Validator::make($input, $rule, $this->vali_msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        $id = $input['id'];
        //判断是否还有子分类
        $is_son = SchoolMenu::where('pid', $id)->count();
        if ($is_son) {
            return $this->error(['-1', '请先删除该菜单下的子菜单']);
        }
        DB::beginTransaction();
        try {
            $m_info = SchoolMenu::find($id);
            if (method_exists($this->model, 'addLog')) {
                $this->model->addLog($m_info->toArray(), [], 3, 'delete');
            }
            SchoolMenu::where('id', $id)->delete();
            AdminCdjAuth::where('menu_id', $id)->delete();
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error();
        }
    }

    public function settingInfo(BaseRequest $request)
    {
        //        $list=AdminSetting::pluck('value','name');
        $list = AdminSetting::get();
        $data = [
            'list' => $list
        ];
        return $this->success($data);
    }

    public function editSetting(BaseRequest $request)
    {
        $input = $request->only('name', 'remark', 'value');
        $rules = [
            'name' => 'required|alpha_dash|exists:admin_setting,name',
            'remark' => [
                'required',
                Rule::unique('admin_setting', 'remark')
                    ->ignore($input['name'], 'name')
            ],
            'value' => 'required',
        ];
        $msg = [];
        $validator = Validator::make($input, $rules, $msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        if (in_array($input['name'], ['pay_forbid_days'])) {
            $pay_notice_days = AdminSetting::where('name', 'pay_notice_days')->value('value');
            if (!is_null($pay_notice_days)) {
                if ($input['value'] <= $pay_notice_days) {
                    return $this->error(['-1', '关闭天数必须大于提醒天数']);
                }
            }
        } elseif ($input['name'] == 'offline_pay_date') {
            if ($input['value'] < 2 || $input['value'] > 28) {
                return $this->error(['-1', '值必须为2到28']);
            }
            $is_run = AdminBillMonth::where('month', 'like', date('Y-m') . '%')->count();
            if (!$is_run && $input['value'] <= date('j')) {
                return $this->error(['-1', '上月账单还未生成，扎帐日期必须大于今日']);
            }
        } elseif ($input['name'] == 'daily_collect_time') {
            if ($input['value'] < 0 || $input['value'] > 24) {
                return $this->error(['-1', '值必须为0到24']);
            }
        }
        DB::beginTransaction();
        try {
            AdminSetting::where('name', $input['name'])->update(['value' => $input['value'], 'remark' => $input['remark']]);
            AdminSetting::addLog([], $input, 2);
            DB::commit();
            return  $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error();
        }
    }

    public function addSetting(BaseRequest $request)
    {
        $input = $request->only('name', 'remark', 'value');
        $rules = [
            'name' => 'required|alpha_dash|unique:admin_setting,name',
            'remark' => 'required|unique:admin_setting,remark',
            'value' => 'required',
        ];
        $msg = [
            'name.unique' => '字段名称已存在',
            'remark.unique' => '备注已存在',
        ];
        $validator = Validator::make($input, $rules, $msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        DB::beginTransaction();
        try {
            $info = AdminSetting::create($input);
            AdminSetting::addLog($info, [], 1);
            DB::commit();
            return  $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error();
        }
    }
}
